<template>
  <div class="main-mail">
    <el-dialog :visible.sync="dialogVisible" width="800px" :close-on-click-modal="false" :close-on-press-escape	='false'
               :title="form.id?'编辑邮件规则':'创建邮件规则'" center>
      <el-form ref="form" :rules="rules" :model="form" label-width="95px" style="margin-top: 20px">
        <div class="line">
        <el-form-item label="规则名称：" prop="name">
          <el-input v-model="form.name" size="small" style="width:200px"
                    placeholder="请输入邮件规则名称"></el-input>
        </el-form-item>
        <el-form-item label="邮箱选择" prop="sendEmail">
          <el-select v-model="form.sendEmail" placeholder="请选择邮箱" size="small">
            <el-option v-for="item in common.emailList" :key="item.emailAddr"
                       :label="item.emailAddr" :value="item.emailAddr"></el-option>
          </el-select>
        </el-form-item>
        </div>
        <div class="line">
          <el-form-item label="是否共享：" prop="isShare">
            <el-radio-group v-model="form.isShare">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否启用：" prop="isEnable">
            <el-radio-group v-model="form.isEnable">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="line">
          <el-form-item label="目标用户组：" prop="groupId">
            <el-select v-model="form.groupId" placeholder="请选择目标用户组" size="small">
              <el-option v-for="item,index in targetGroup" :key="index"
                         :label="item.className" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="添加事件：" prop="groupId">
            <el-button size="small" type="primary" @click="add">+ 新增</el-button>
          </el-form-item>
        </div>
      </el-form>
      <div v-show="eventList.length>0">
        <el-table :data="eventList"
                  style="width: 100%;margin-top: 15px;max-height: 200px;overflow-y: scroll">
          <el-table-column label="客户类型">
            <template slot-scope="scope">
              {{deal(1,scope.row.cutGroupId)}}
            </template>
          </el-table-column>
          <el-table-column label="时间间隔" prop="intervalTime">
            <template slot-scope="scope">
              {{scope.row.intervalTime}}秒
            </template>
          </el-table-column>
          <el-table-column label="邮件模板">
            <template slot-scope="scope">
              <span class="more">{{deal(2,scope.row.templateId)}}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="delRow(scope.row.index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer" align="right">
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" size="mini" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogEvent" title="新增事件" center width="500px">
      <el-form ref="formEvent" :rules="rulesEvent" :model="formEvent" label-width="100px" style="margin-top: 20px">
        <el-form-item label="时间间隔：" prop="time">
          <el-select v-model="formEvent.time" placeholder="请选择时间间隔">
            <el-option v-for="item,index in timeRule" :key="index"
                       :label="item.intervalValue+filterTime(item.intervalUnit)"
                       :value="item.intervalValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模 板：" prop="templateId">
          <el-select v-model="formEvent.templateId" placeholder="请选择模板">
            <el-option v-for="item,index in templateGroup" :key="index"
                       :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="right">
        <el-button @click="dialogEvent = false" size="mini">取 消</el-button>
        <el-button type="primary" size="mini" @click="addEvent">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import {saveRules, updateRule, getTargetGroup, getTimeRule} from "@/api/mailAutomation"
    import {mailList} from "@/api/automation/mail"
    import {mapState} from 'vuex'

    export default {
        name: "SocialDialog",
        data() {
            return {
                dialogVisible: false,
                form: {
                    name: '',
                    isShare: true,
                    isEnable: true,
                    groupId: '',
                    emailSubrules: [],//事件组
                    sendEmail: ''
                },
                rules: {
                    name: {required: true, message: '请输入规格名称', trigger: 'blur'},
                    sendEmail: {required: true, message: '请选择邮箱', trigger: 'blur'},
                    isShare: {required: true, message: '请选择是否共享', trigger: 'blur'},
                    isEnable: {required: true, message: '请选择是否启用', trigger: 'blur'},
                    groupId: {required: true, message: '请选择目标用户组', trigger: 'blur'},
                },
                dialogEvent: false,
                formEvent: {
                    time: '',
                    templateId: ''
                },
                rulesEvent: {
                    type: {required: true, message: '请选择客户类型', trigger: 'blur'},
                    time: {required: true, message: '请选择时间间隔', trigger: 'blur'},
                    templateId: {required: true, message: '请选择邮件模板', trigger: 'blur'},
                },
                targetGroup: [],
                timeRule: [],
                templateGroup: [],
                eventList: []
            }
        },
        computed: {
            ...mapState(['common'])
        },
        mounted() {
            //获取目标用户组
            this.getInfo();
        },
        methods: {
            //提交
            submit() {
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        const param = Object.assign({}, this.form, {
                            emailSubrules: this.eventList
                        })
                        if (this.form.id) {//保存
                            updateRule(param).then(res => {
                                this.dealResult(res)
                            })
                        } else {//新增
                            saveRules(param).then(res => {
                                this.dealResult(res)
                            })
                        }
                    } else {
                        return false;
                    }
                });

            },
            //获取目标用户组
            getInfo() {
                getTargetGroup().then(res => {
                    if(res.data.success){
                        this.targetGroup = res.data.data;
                    }

                })
                getTimeRule().then(res => {
                    if(res.data.success){
                        this.timeRule = res.data.data;
                    }
                })
                mailList('',1, 100,'').then(res => {
                    if(res.data.success){
                        this.templateGroup = res.data.data.records
                    }
                })
            },
            //重置
            reset(params) {
                if(this.templateGroup.length==0){
                    this.$confirm('您还尚未创建邮件模板，立即去创建', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: "success"
                    }).then(() => {
                        this.$router.push('/automation/template/mailDetail/-1')
                    }).catch(() => {
                    });
                    return;
                }
                if (params) {//编辑
                    this.form = JSON.parse(JSON.stringify(Object.assign({}, this.form, params))) //简单深拷贝
                    this.form.emailSubrules.map((item, index) => {
                        item.index = index;
                    })
                    this.eventList = this.form.emailSubrules
                } else {
                    this.form = {
                        name: '',
                        isShare: true,
                        isEnable: true,
                        groupId: '',
                        emailSubrules: [],//事件组
                    }
                    if(this.$refs.form){
                        this.$refs.form.resetFields();
                    }
                    this.eventList = []
                }
                this.dialogVisible = true;
            },
            delRow(index) {
                this.eventList.splice(index, 1)
            },
            //添加事件
            addEvent() {
                this.$refs['formEvent'].validate((valid) => {
                    if (valid) {
                        const obj = {
                            cutGroupId: this.form.groupId,
                            intervalTime: this.formEvent.time,
                            templateId: this.formEvent.templateId
                        };
                        this.eventList.push(obj)
                        this.dialogEvent = false;
                    } else {
                        return false;
                    }
                });
            },
            add() {
                if (!this.form.groupId) {
                    this.$message({
                        type: "success",
                        message: '请先选择目标用户组'
                    });
                    return;
                }
                if (this.$refs.formEvent) {
                    this.$refs.formEvent.resetFields();
                }
                this.dialogEvent = true;
            },
            dealResult(res) {
                if(res.data.success){
                    this.$message({
                        type: 'success',
                        message: res.data.msg
                    });
                    this.dialogVisible = false;
                    this.$emit('getList')
                }else{
                    this.$message({
                        type: "success",
                        message: res.data.msg
                    });
                }

            },
            deal(type, id) {
                let name;
                if (type == 1) {
                    this.targetGroup.map(item => {
                        if (item.id == id) {
                            name = item.className
                            return;
                        }
                    })
                } else {
                    this.templateGroup.map(item => {
                        if (item.id == id) {
                            name = item.name;
                            return;
                        }
                    })
                }
                return name;
            },
            filterTime(type) {
                switch (type) {
                    case 0:
                        return '秒';
                    case 1:
                        return '分';
                    case 2:
                        return '小时';
                    default:
                        return null
                }
            }
        }
    }
</script>

<style  lang="scss">
  .main-mail {
    width: 90%;
    margin: 20px auto 0;

    .line {
      display: flex;

      .el-form-item {
        width: 50%;
        .el-form-item__label{
          padding: 0;
          text-align: left;
        }
      }
    }

  }
</style>
